/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lovetransferjia.chatuidemo;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.text.Html.ImageGetter;
import android.util.Log;

import com.easemob.chat.ConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.OnNotificationClickListener;
import com.lovetransferjia.chatuidemo.activity.ChatActivity;
import com.lovetransferjia.chatuidemo.activity.MainActivity;
import com.lovetransferjia.chatuidemo.db.DbOpenHelper;
import com.lovetransferjia.chatuidemo.db.UserDao;
import com.lovetransferjia.chatuidemo.domain.User;
import com.lovetransferjia.chatuidemo.utils.PreferenceUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.renn.rennsdk.RennClient;
import com.umeng.analytics.MobclickAgent;

public class MyApplication extends Application {
	// ==========================================
	public static CookieStore localCookies = null;
	public static HttpContext localContext = null;
	public static DefaultHttpClient httpClient = null;
	public static String uid = "0";
	static public String baseUrl = "http://lovetransfer.duapp.com/index.php/"; //服务器基地址
	static public String postfix = "/format/json"; 
	public static String appName = "LoveTransfer.apk";
	public static String app = "LoveTransfer";
	public static String apppostfix = ".apk";
	public static String updateUrl = "http://jiady.sinaapp.com/" + appName; 
	public static String updateBaseUrlString = "http://jiady.sinaapp.com/lovetransfer/"; //更新版本的网址
	public static String updateCheckurlString=updateBaseUrlString+"version.html"; //检查最新版本
	public static ImageLoader imageLoader;
	public static int serverVersion = 1;
	public static int localVersion = 10000;
	public static DisplayImageOptions noCacheOptions;
	public static ImageGetter imageGetter;
	public static HashMap<String, Integer> picHashMap;
	public static int randomSeed = 0;
	public static int randomSeed2 = 0;
	public static int picnumber = 25;
	public static int screenWidth = 0, screenHeight = 0;
	public static String myrealname = "";
	public static String mypic = "";

	public static String RenrenAPPID="272723"; //人人应用对应的参数
	public static String RenrenAKEY="1c83c4a958bc4a1995a068a446b62576";
	public static String RenrenSKEY="6a933f4de3e6418593b24d01c5e99291";
	// ==========================================
	public static String id=null;
	public static String name=null;
	public static String school=null;
	public static String major=null;
	public static String headimage=null;
	public static String profile=null;
	public static String gender=null;
	public static String city=null;
	public static String hobby=null;
	private static String lovename=null;
	private static String lovepwd=null;
	public static String match_id="0";
	public static String match_image=null;
	public static String my_image=null;
	
	
	
	// ==========================================
	public static String my_name=null,my_id=null,my_school=null,my_major=null,my_bio=null,my_img=null,my_active=null;
	public static String M_name=null,M_id=null,M_school=null,M_major=null,M_bio=null,M_img=null,M_active=null;
	
	
	
	// ==========================================
	
	
	// ==========================================

	public static Context applicationContext;
	private static MyApplication instance;
	// login user name
	public final String PREF_USERNAME = "username";
	private String userName = null;
	// login password
	private static final String PREF_PWD = "pwd";
	private String password = null;
	private Map<String, User> contactList;
	public static RennClient rennClient = null;

	@Override
	public void onCreate() {
		super.onCreate();
		rennClient = RennClient.getInstance(this);
		rennClient.init("272723", "1c83c4a958bc4a1995a068a446b62576",
				"6a933f4de3e6418593b24d01c5e99291");// 设置应用程序信息
		rennClient.setScope("read_user_album read_user_status publish_feed");
		rennClient.setTokenType("mac"); 
		
		DisplayImageOptions doptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true).cacheOnDisc(true).considerExifParams(true)
				.build();
		noCacheOptions = new DisplayImageOptions.Builder().build();
		
		ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(
				this).discCacheSize(50 * 1024 * 1024).discCacheFileCount(10)
				.defaultDisplayImageOptions(doptions).build();
		
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(imageLoaderConfiguration);
		localCookies = new BasicCookieStore();
		httpClient = new DefaultHttpClient();
		localContext = new BasicHttpContext();
		localContext.setAttribute(ClientContext.COOKIE_STORE, localCookies);

		int pid = android.os.Process.myPid();
		String processAppName = getAppName(pid);
		// 如果使用到百度地图或者类似启动remote service的第三方库，这个if判断不能少
		if (processAppName == null || processAppName.equals("")) {
			// workaround for baidu location sdk
			// 百度定位sdk，定位服务运行在一个单独的进程，每次定位服务启动的时候，都会调用application::onCreate
			// 创建新的进程。
			// 但环信的sdk只需要在主进程中初始化一次。 这个特殊处理是，如果从pid 找不到对应的processInfo
			// processName，
			// 则此application::onCreate 是被service 调用的，直接返回
			return;
		}
		applicationContext = this;
		instance = this;
		// 初始化环信SDK,一定要先调用init()
		Log.d("EMChat Demo", "initialize EMChat SDK");
		EMChat.getInstance().init(applicationContext);
		// debugmode设为true后，就能看到sdk打印的log了
		EMChat.getInstance().setDebugMode(true);

		// 获取到EMChatOptions对象
		EMChatOptions options = EMChatManager.getInstance().getChatOptions();
		// 默认添加好友时，是不需要验证的，改成需要验证
		options.setAcceptInvitationAlways(false);
		// 设置收到消息是否有新消息通知，默认为true
		options.setNotificationEnable(PreferenceUtils.getInstance(
				applicationContext).getSettingMsgNotification());
		// 设置收到消息是否有声音提示，默认为true
		options.setNoticeBySound(PreferenceUtils
				.getInstance(applicationContext).getSettingMsgSound());
		// 设置收到消息是否震动 默认为true
		options.setNoticedByVibrate(PreferenceUtils.getInstance(
				applicationContext).getSettingMsgVibrate());
		// 设置语音消息播放是否设置为扬声器播放 默认为true
		options.setUseSpeaker(PreferenceUtils.getInstance(applicationContext)
				.getSettingMsgSpeaker());
		// 设置notification消息点击时，跳转的intent为自定义的intent
		options.setOnNotificationClickListener(new OnNotificationClickListener() {

			@Override
			public Intent onNotificationClick(EMMessage message) {
				Intent intent = new Intent(applicationContext,
						ChatActivity.class);
				ChatType chatType = message.getChatType();
				if (chatType == ChatType.Chat) { // 单聊信息
					intent.putExtra("userId", message.getFrom());
					intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE);
				} else { // 群聊信息
							// message.getTo()为群聊id
					intent.putExtra("groupId", message.getTo());
					intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
				}
				return intent;
			}
		});
		// 设置一个connectionlistener监听账户重复登陆
		EMChatManager.getInstance().addConnectionListener(
				new MyConnectionListener());
		// 取消注释，app在后台，有新消息来时，状态栏的消息提示换成自己写的
		// options.setNotifyText(new OnMessageNotifyListener() {
		//
		// @Override
		// public String onNewMessageNotify(EMMessage message) {
		// //可以根据message的类型提示不同文字，demo简单的覆盖了原来的提示
		// return "你的好基友" + message.getFrom() + "发来了一条消息哦";
		// }
		//
		// @Override
		// public String onLatestMessageNotify(EMMessage message, int
		// fromUsersNum, int messageNum) {
		// return fromUsersNum + "个基友，发来了" + messageNum + "条消息";
		// }
		// });

	
	}

	public static MyApplication getInstance() {
		return instance;
	}

	// List<String> list = new ArrayList<String>();
	// list.add("1406713081205");
	// options.setReceiveNotNoifyGroup(list);
	/**
	 * 获取内存中好友user list
	 * 
	 * @return
	 */
	public Map<String, User> getContactList() {
		if (getUserName() != null && contactList == null) {
			UserDao dao = new UserDao(applicationContext);
			// 获取本地好友user list到内存,方便以后获取好友list
			contactList = dao.getContactList();
		}
		return contactList;
	}

	/**
	 * 设置好友user list到内存中
	 * 
	 * @param contactList
	 */
	public void setContactList(Map<String, User> contactList) {
		this.contactList = contactList;
	}

	public void setStrangerList(Map<String, User> List) {

	}

	/**
	 * 获取当前登陆用户名
	 * 
	 * @return
	 */
	public String getMatch() {
		if (match_id   == null || match_id.equals("0")) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			match_id = preferences.getString("match_id", "0");
		}
		return match_id;
	}
	public void setMatch(String localMatchId) {
		if (localMatchId != null && !localMatchId.equals("0")) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			SharedPreferences.Editor editor = preferences.edit();
			if (editor.putString("match_id", localMatchId).commit()) {
				match_id = localMatchId;
			}
		}
	}
	
	
	public String getUserName() {
		if (userName == null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			userName = preferences.getString(PREF_USERNAME, null);
		}
		return userName;
	}
	public String getLoveName() {
		if (lovename == null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			lovename = preferences.getString("lovename", null);
		}
		return lovename;
	}

	/**
	 * 获取密码
	 * 
	 * @return
	 */
	public String getPassword() {
		if (password == null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			password = preferences.getString(PREF_PWD, null);
		}
		return password;
	}
	public String getLovepwd() {
		if (lovepwd == null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			lovepwd  = preferences.getString("lovepwd" , null);
		}
		return lovepwd ;
	}

	/**
	 * 设置用户名
	 * 
	 * @param user
	 */
	public void setUserName(String username) {
		if (username != null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			SharedPreferences.Editor editor = preferences.edit();
			if (editor.putString(PREF_USERNAME, username).commit()) {
				userName = username;
			}
		}
	}
	public void setLoveName(String username) {
		if (username != null) {
			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(applicationContext);
			SharedPreferences.Editor editor = preferences.edit();
			if (editor.putString("lovename", username).commit()) {
				lovename = username;
			}
		}
	}

	/**
	 * 设置密码 下面的实例代码 只是demo，实际的应用中需要加password 加密后存入 preference 环信sdk
	 * 内部的自动登录需要的密码，已经加密存储了
	 * 
	 * @param pwd
	 */
	public void setPassword(String pwd) {
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(applicationContext);
		SharedPreferences.Editor editor = preferences.edit();
		if (editor.putString(PREF_PWD, pwd).commit()) {
			password = pwd;
		}
	}
	public void setLovepwd(String pwd) {
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(applicationContext);
		SharedPreferences.Editor editor = preferences.edit();
		if (editor.putString("lovepwd", pwd).commit()) {
			lovepwd = pwd;
		}
	}

	/**
	 * 退出登录,清空数据
	 */
	public void logout() {
		// 先调用sdk logout，在清理app中自己的数据
		EMChatManager.getInstance().logout();
		DbOpenHelper.getInstance(applicationContext).closeDB();
		// reset password to null
		setPassword(null);
		setLoveName(null);
		setLovepwd(null);
		setUserName(null);
		setContactList(null);
		id=null;
		name=null;
		school=null;
		major=null;
		headimage=null;
		profile=null;
		gender=null;
		city=null;
		hobby=null;
		lovename=null;
		lovepwd=null;
		my_name=null;
		my_bio=null;
		my_id=null;
		my_img=null;
		my_major=null;
		my_school=null;
		M_name=null;
		M_major=null;
		M_school=null;
		M_img=null;
		M_bio=null;

	}

	private String getAppName(int pID) {
		String processName = null;
		ActivityManager am = (ActivityManager) this
				.getSystemService(ACTIVITY_SERVICE);
		List l = am.getRunningAppProcesses();
		Iterator i = l.iterator();
		PackageManager pm = this.getPackageManager();
		while (i.hasNext()) {
			ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i
					.next());
			try {
				if (info.pid == pID) {
					CharSequence c = pm.getApplicationLabel(pm
							.getApplicationInfo(info.processName,
									PackageManager.GET_META_DATA));
					// Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
					// info.processName +"  Label: "+c.toString());
					// processName = c.toString();
					processName = info.processName;
					return processName;
				}
			} catch (Exception e) {
				// Log.d("Process", "Error>> :"+ e.toString());
			}
		}
		return processName;
	}

	class MyConnectionListener implements ConnectionListener {
		@Override
		public void onReConnecting() {
		}

		@Override
		public void onReConnected() {
		}

		@Override
		public void onDisConnected(String errorString) {
			if (errorString != null && errorString.contains("conflict")) {
				Intent intent = new Intent(applicationContext,
						MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("conflict", true);
				startActivity(intent);
			}

		}

		@Override
		public void onConnecting(String progress) {

		}

		@Override
		public void onConnected() {
		}
	}
}
